__version__ = 1.2
import ticker as burner
import webbrowser
#import threading
try:
    from Tkinter import * #Python 2
except:
    from tkinter import * #Python 3
ENGLISH = 1
GERMAN = 2
class Application(Frame):
    def __init__(self,settings, master = None):
        Frame.__init__(self, master)
        #self.
        self.settings = settings
        self.grid()
        self.get_data()
        self.create_labels()
        self.create_entries()
        self.create_buttons()
        self.make_layout()
        self.calibrated = 0
        self.statustext = "uncalibrated"
        self.language = ENGLISH
    def make_layout(self):
        self.grid_columnconfigure(0, minsize = 200)
        self.grid_columnconfigure(1, minsize = 70)
        for x in range(6):
            self.grid_rowconfigure(x, minsize = 26)
            
    def create_entries(self):
        self.freqentry = Entry(self)
        self.freqentry["width"] = 7
        self.freqentry.insert(0, 2.0)
        self.freqentry.grid(sticky = E, row = 4)
        self.timeentry = Entry(self)
        self.timeentry["width"] = 7
        self.timeentry.insert(0, 60)
        self.timeentry.grid(sticky = E, row = 2)
        
    def open_3dcenter(self):
        webbrowser.open("http://www.3dcenter.org/")
    def change_language(self):
        if self.language == ENGLISH:
            self.language = GERMAN
        else:
            self.language = ENGLISH
        self.update_labels()
        
    def create_buttons(self):
        self.threedcenterbutton = Button(self, text = "3DCenter",
                                     command = self.open_3dcenter)

        self.languagebutton = Button(self, text = "GER",
                                     command = self.change_language)
        self.calibutton = Button(self, text = "Calibrate",
                                  command = self.start_button_func)
        self.applybutton = Button(self, text = "Apply",
                                  command = self.update_values)
        self.apply2button = Button(self, text = "Apply",
                                  command = self.update_values)
        self.threedcenterbutton.grid(column = 1,row = 5)
        self.languagebutton.grid(column = 1, row = 0)

        self.applybutton.grid(column = 1, row = 2)
        self.apply2button.grid(column = 1, row = 4)
        self.calibutton.grid(column = 1, row = 1)

    def start_button_func(self):
        if self.calibrated == 0:
            if self.language == ENGLISH:
                self.statustext = "calibrating *busy*"
            else:
                self.statustext = "kalibriere *beschäftigt*"
            self.update_labels(True)
            self.update_idletasks()
            self.calibrate()
        else:
            if self.language == ENGLISH:
                self.statustext = "running *busy*"
            else:
                self.statustext = "laufe *beschäftigt*"
            self.update_labels(True)
            self.update_idletasks()
            burner.test(self.settings, self.show_remaining_time)
            #self.statustext = "ready"
            #self.update_labels(True)
        self.update_labels()
        self.update_idletasks()
    def get_data(self):
        self.cpucount = self.settings.cpucount
        self.stress = self.settings.stress
        self.cycletime = self.settings.cycletime
        self.testtime = self.settings.testtime
        self.calibrated = self.settings.calibrated
        if self.calibrated == 0:
            self.statustext = "uncalibrated"
            
    def calibrate(self):
        #self.statustext = "calibrating *busy*"
        #self.update_labels()
        #self.update_idletasks()
        burner.calibration(self.settings)
        self.get_data()
        self.update_labels()
        
    def reset_entries(self):
        self.freqentry.delete(0, END)
        self.freqentry.insert(0, 1/self.cycletime)
        self.timeentry.delete(0, END)
        self.timeentry.insert(0, self.testtime)
        
    def update_values(self):
        strtime = self.timeentry.get()
        try:
            time = int(strtime)
            self.settings.testtime = time
        except: self.reset_entries()
        strfreq = self.freqentry.get()
        try:
            freq = float(strfreq)
            self.settings.cycletime = 1/freq
        except:
            self.reset_entries()
        self.settings.calibrated = 0
        self.norm_settings()
        self.get_data()
        self.update_labels()
    def norm_settings(self):
        self.settings.cycletime = min_max(0.01, self.settings.cycletime, 10)
        self.settings.testtime = min_max(10, self.settings.testtime, 600)
    def show_remaining_time(self, time_elapsed):
        if self.language == ENGLISH:
            self.i.config(text = "Remaining time : "+str(int(round(
                self.testtime-time_elapsed)))+" seconds")
        else:
            self.i.config(text = "Restzeit : "+str(int(round(
                self.testtime-time_elapsed)))+" Sekunden")
        #self.update_idletasks()
        self.i.update()

    def update_labels(self, statustext_overwrite = False, time_elasped = 0):
        if not statustext_overwrite:
            if self.settings.calibrated == 3:
                if self.language == ENGLISH:
                    self.statustext = "frequency too high"
                else:
                    self.statustext = "Frequenz zu hoch"
                self.calibutton.config(text = "Start Test")
            elif self.settings.calibrated == 1:
                if self.language == ENGLISH:
                    self.statustext = "ready"
                else:
                    self.statustext = "bereit"
                self.calibutton.config(text = "Start Test")
            elif self.settings.calibrated == 0:
                if self.language == ENGLISH:
                    self.statustext = "uncalibrated"
                    self.calibutton.config(text = "Calibrate")
                else:
                    self.statustext = "unkalibriert"
                    self.calibutton.config(text = "Kalibrieren")
            elif self.settings.calibrated == 2:
                if self.language == ENGLISH:
                    self.statustext = "exceeded tolerance"
                else:
                    self.statustext = "Toleranz überschritten"
                self.calibutton.config(text = "Start Test")
            else:
                if self.language == ENGLISH:
                    self.statustext = "unknown error"
                else:
                    self.statustext = "unbekannter Fehler"
                self.calibutton.config(text = "Start Test")
        self.s.config(text = "Status : "+self.statustext)
        self.w.config(text = "Stress : "+str(self.stress))
        if self.language == ENGLISH:
            #if time_elasped != 0:
            self.i.config(text = "Testtime : "+str(self.testtime)+" seconds")
            self.u.config(text = "Time for one cycle : "+str(round(self.cycletime, 4))+" seconds")
            self.f.config(text = "Frequency : "+str(1/self.cycletime)+" hertz")
            self.c.config(text = "CPU Count : "+str(self.cpucount))
            self.languagebutton.config(text = "GER")
            self.apply2button.config(text = "Apply")
            self.applybutton.config(text = "Apply")            
        else:
            self.i.config(text = "Testzeit : "+str(self.testtime)+" Sekunden")
            self.u.config(text = "Zeit für eine Schwingung : "+str(round(self.cycletime, 4))+" Sekunden")
            self.f.config(text = "Frequenz : "+str(1/self.cycletime)+" Hertz")
            self.c.config(text = "CPU Kernmenge : "+str(self.cpucount))
            self.languagebutton.config(text = "ENG")
            self.apply2button.config(text = "Setzen")
            self.applybutton.config(text = "Setzen")
    def create_labels(self):
        self.w = Label(self, text = "Stress : "+str(self.stress))
        self.s = Label(self, text = "Status : uncalibrated")
        self.i = Label(self, text = "Testtime : "+str(self.testtime)+" seconds")
        self.c = Label(self, text = "CPU Count : "+str(self.cpucount))
        
        self.u = Label(self,
                       text = "Time for one cycle : "+str(self.cycletime)+" seconds")
        self.f = Label(self,
                       text = "Frequency : "+str(1/self.cycletime)+" hertz")
        self.s.grid(sticky = W, column = 0)
        self.c.grid(sticky = W, column = 0)
        self.i.grid(sticky = W, column = 0)
        self.u.grid(sticky = W, column = 0)
        self.f.grid(sticky = W, column = 0)
        self.w.grid(sticky = W, column = 0)
        
def start(settings):
    root = Tk()
    root.wm_iconbitmap('favicon.ico')
    root.resizable(0,0)
    gui = Application(settings, root)
    gui.master.title("3DCenter CPU Ticker "+str(__version__))
    gui.mainloop()
    
def min_max(min_value, value, max_value):
    if min_value > value:
        value = min_value
    elif max_value < value:
        value = max_value
    return value
